<template>
  <div class="profile-container">
    <button class="back-home-btn" @click="goHome">返回首页</button>
    <div class="profile-layout">
      <!-- 左侧菜单 -->
      <aside class="profile-sidebar">
        <div class="avatar-box">
          <img class="avatar" :src="getAvatarUrl(user.avatar)" alt="头像">
          <div class="username">{{ user.username || '未登录' }}</div>
        </div>
        <ul class="profile-menu">
          <li :class="{active: activeTab==='base'}" @click="activeTab='base'">基础信息</li>
          <li :class="{active: activeTab==='favorites'}" @click="activeTab='favorites'">我的收藏</li>
          <li :class="{active: activeTab==='history'}" @click="activeTab='history'">浏览历史</li>
          <li :class="{active: activeTab==='addresses'}" @click="activeTab='addresses'">我的地址</li>
          <li class="logout-btn" @click="handleLogout">退出登录</li>
        </ul>
      </aside>
      <!-- 右侧内容区 -->
      <main class="profile-main">
        <div v-if="activeTab==='base'">
          <form class="base-info-form" @submit.prevent="saveBaseInfo">
            <div class="form-row">
              <label>用户名</label>
              <input v-model="editUser.username" required />
            </div>
            <div class="form-row">
              <label>邮箱</label>
              <input v-model="editUser.email" type="email" required />
            </div>
            <div class="form-row">
              <label>手机号</label>
              <input v-model="editUser.phone" />
            </div>
            <div class="form-row">
              <label>学号</label>
              <input v-model="editUser.studentId" disabled />
            </div>
            <div class="form-row">
              <label>头像</label>
              <div class="avatar-upload-box">
                <img :src="getAvatarUrl(editUser.avatar)" class="avatar-preview" alt="头像预览" />
                <input type="file" accept="image/*" @change="onAvatarChange" />
              </div>
            </div>
            <button class="save-btn" type="submit">保存修改</button>
            <span v-if="baseInfoMsg" class="base-info-msg">{{ baseInfoMsg }}</span>
          </form>
        </div>
        <div v-else-if="activeTab==='favorites'">
          <div v-if="favoritesLoading">加载中...</div>
          <ul v-else>
            <li v-for="item in favorites" :key="item.product_id">{{ item.title }}</li>
            <li v-if="favorites.length===0">暂无收藏</li>
          </ul>
        </div>
        <div v-else-if="activeTab==='history'">
          <div v-if="historyLoading">加载中...</div>
          <ul v-else>
            <li v-for="item in history" :key="item.history_id">{{ item.title }}</li>
            <li v-if="history.length===0">暂无浏览记录</li>
          </ul>
        </div>
        <div v-else-if="activeTab==='addresses'">
          <h2>我的地址</h2>
          <div class="address-list">
            <div v-for="address in addresses" :key="address.address_id" class="address-item" :class="{ 'default-address': address.is_default }">
              <div class="address-info">
                <div class="address-recipient">{{ address.recipient }} {{ address.phone }}</div>
                <div class="address-detail">{{ address.province }} {{ address.city }} {{ address.campus }} {{ address.detail_address }}</div>
              </div>
              <div class="address-actions">
                <span v-if="address.is_default" class="default-tag">🏠 默认地址</span>
                <button @click="setDefaultAddress(address.address_id)" v-if="!address.is_default">设为默认</button>
                <button @click="editAddress(address.address_id)">编辑</button>
                <button @click="deleteAddress(address.address_id)">删除</button>
              </div>
            </div>
            <div v-if="addresses.length === 0" class="no-address">暂无地址，请添加新地址</div>
          </div>
          <button class="add-address-btn" @click="showAddAddressForm">添加新地址</button>
          <div v-if="showAddressForm" class="address-form-container">
            <form class="address-form" @submit.prevent="saveAddress">
              <div class="form-row">
                <label>收件人</label>
                <input v-model="currentAddress.recipient" required />
              </div>
              <div class="form-row">
                <label>联系电话</label>
                <input v-model="currentAddress.phone" required />
              </div>
              <div class="form-row">
                <label>省份</label>
                <input v-model="currentAddress.province" required />
              </div>
              <div class="form-row">
                <label>城市</label>
                <input v-model="currentAddress.city" required />
              </div>
              <div class="form-row">
                <label>校区</label>
                <input v-model="currentAddress.campus" required />
              </div>
              <div class="form-row">
                <label>详细地址</label>
                <input v-model="currentAddress.detail_address" required />
              </div>
              <div class="form-row">
                <label>设为默认地址</label>
                <input type="checkbox" v-model="currentAddress.is_default" />
              </div>
              <div class="form-buttons">
                <button type="submit">保存</button>
                <button type="button" @click="showAddressForm=false">取消</button>
              </div>
            </form>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const goHome = () => {
  router.push('/');
};
import { ref, onMounted, watch } from 'vue';
import axios from 'axios';

const defaultAvatar = '';

const user = ref({ username: '', avatar: '', email: '', phone: '', studentId: '' });
const editUser = ref({ username: '', avatar: '', email: '', phone: '', studentId: '' });
const activeTab = ref('base');
const baseInfoMsg = ref('');
const favorites = ref<any[]>([]);
const favoritesLoading = ref(false);
const history = ref<any[]>([]);
const historyLoading = ref(false);
// 添加缺少的变量定义
const addresses = ref<any[]>([]);
const addressesLoading = ref(false);
const currentAddress = ref<{ recipient: string; phone: string; province: string; city: string; campus: string; detail_address: string; is_default: boolean; address_id: string }>({
  recipient: '',
  phone: '',
  province: '',
  city: '',
  campus: '',
  detail_address: '',
  is_default: false,
  address_id: ''
});
const showAddressForm = ref(false);
const addressMsg = ref('');

const fetchProfile = async () => {
  const token = localStorage.getItem('token');
  try {
    const res = await axios.get('/api/auth/profile', {
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      }
    });
    user.value = res.data.user || { username: '', avatar: '', email: '', phone: '', studentId: '' };
    Object.assign(editUser.value, user.value);
  } catch (err: any) {
    user.value = { username: '', avatar: '', email: '', phone: '', studentId: '' };
  }
};

onMounted(() => {
  fetchProfile();
});

const saveBaseInfo = async () => {
  baseInfoMsg.value = '';
  const token = localStorage.getItem('token');
  try {
    const res = await axios.post('/api/auth/update', editUser.value, {
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      }
    });
    if (res.data.success) {
      baseInfoMsg.value = '保存成功';
      fetchProfile();
    } else {
      baseInfoMsg.value = res.data.message || '保存失败';
      console.error('保存基础信息失败:', res.data);
    }
  } catch (err: any) {
    console.error('保存基础信息异常:', err, err?.response?.data);
    baseInfoMsg.value = err.response?.data?.message || '保存失败';
  }
};

const fetchFavorites = async () => {
  favoritesLoading.value = true;
  const token = localStorage.getItem('token');
  try {
    const res = await axios.get('/api/auth/favorites', {
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      }
    });
    favorites.value = res.data.favorites || [];
  } catch {
    favorites.value = [];
  }
  favoritesLoading.value = false;
};

const fetchHistory = async () => {
  historyLoading.value = true;
  const token = localStorage.getItem('token');
  try {
    const res = await axios.get('/api/auth/history', {
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      }
    });
    history.value = res.data.history || [];
  } catch {
    history.value = [];
  }
  historyLoading.value = false;
};

const fetchAddresses = async () => {
  addressesLoading.value = true;
  const token = localStorage.getItem('token');
  try {
    const res = await axios.get('/api/auth/addresses', {
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      }
    });
    // 将is_default从数字类型转换为布尔类型
    addresses.value = res.data.addresses.map((address: any) => ({
      ...address,
      is_default: address.is_default === 1
    })) || [];
  } catch {
    addresses.value = [];
  }
  addressesLoading.value = false;
};

const showAddAddressForm = () => {
  currentAddress.value = { recipient: '', phone: '', province: '', city: '', campus: '', detail_address: '', is_default: false, address_id: '' };
  showAddressForm.value = true;
};

const editAddress = (addressId: string) => {
  const address = addresses.value.find(a => a.address_id === addressId);
  if (address) {
    // 确保is_default是布尔类型
    currentAddress.value = {
      ...address,
      is_default: address.is_default === 1
    };
    showAddressForm.value = true;
  }
};

const saveAddress = async () => {
  addressMsg.value = '';
  const token = localStorage.getItem('token');
  try {
    const res = currentAddress.value.address_id
      ? await axios.put(`/api/auth/addresses/${currentAddress.value.address_id}`, currentAddress.value, {
          headers: {
            ...(token ? { 'Authorization': `Bearer ${token}` } : {})
          }
        })
      : await axios.post('/api/auth/addresses', currentAddress.value, {
          headers: {
            ...(token ? { 'Authorization': `Bearer ${token}` } : {})
          }
        });

    if (res.data.success) {
      addressMsg.value = currentAddress.value.address_id ? '更新成功' : '添加成功';
      showAddressForm.value = false;
      fetchAddresses();
    } else {
      addressMsg.value = res.data.message || '操作失败';
    }
  } catch (err: any) {
    addressMsg.value = err.response?.data?.message || '操作失败';
  }
};

const deleteAddress = async (addressId: string) => {
  if (!confirm('确定要删除这个地址吗？')) return;
  const token = localStorage.getItem('token');
  try {
    const res = await axios.delete(`/api/auth/addresses/${addressId}`, {
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      }
    });
    if (res.data.success) {
      fetchAddresses();
    } else {
      alert(res.data.message || '删除失败');
    }
  } catch (err: any) {
    alert(err.response?.data?.message || '删除失败');
  }
};

const setDefaultAddress = async (addressId: string) => {
  const token = localStorage.getItem('token');
  try {
    const res = await axios.post(`/api/auth/addresses/${addressId}/default`, {}, {
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      }
    });
    if (res.data.success) {
      fetchAddresses();
    } else {
      alert(res.data.message || '设置失败');
    }
  } catch (err: any) {
    alert(err.response?.data?.message || '设置失败');
  }
};

watch(activeTab, (tab) => {
  if (tab === 'favorites') fetchFavorites();
  if (tab === 'history') fetchHistory();
  if (tab === 'addresses') fetchAddresses();
});

const handleLogout = async () => {
  const token = localStorage.getItem('token');
  try {
    const res = await axios.post('/api/auth/logout', {}, {
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      }
    });
    if (res.status === 200 && res.data.message === '登出成功') {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    } else {
      alert(res.data.message || '退出登录失败');
    }
  } catch (err) {
    const e = err as any;
    alert((e.response && e.response.data && e.response.data.message) || '网络错误，退出登录失败');
  }
};

const onAvatarChange = async (e: Event) => {
  const files = (e.target as HTMLInputElement).files;
  if (!files || files.length === 0) return;
  const file = files[0];
  const token = localStorage.getItem('token');
  const formData = new FormData();
  formData.append('avatar', file);
  try {
    const res = await axios.post('/api/auth/avatar', formData, {
      headers: {
        ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
        'Content-Type': 'multipart/form-data'
      }
    });
    if (res.data.success && res.data.url) {
      editUser.value.avatar = res.data.url;
      baseInfoMsg.value = '头像上传成功';
      // 同步 localStorage.user，确保导航栏实时显示新头像
      const userStr = localStorage.getItem('user');
      if (userStr) {
        const userObj = JSON.parse(userStr);
        userObj.avatar = res.data.url;
        localStorage.setItem('user', JSON.stringify(userObj));
      }
    } else {
      baseInfoMsg.value = res.data.message || '头像上传失败';
      console.error('头像上传失败:', res.data);
    }
  } catch (err: any) {
    console.error('头像上传异常:', err, err?.response?.data);
    baseInfoMsg.value = err.response?.data?.message || '头像上传失败';
  }
};

// 拼接完整头像地址
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000';
const getAvatarUrl = (avatar: string) => {
  if (!avatar) return defaultAvatar;
  if (avatar.startsWith('http') || avatar.startsWith('data:')) return avatar;
  if (avatar.startsWith('/uploads/')) return API_BASE + avatar;
  return defaultAvatar;
};
</script>

<style scoped>
.back-home-btn {
  position: fixed;
  top: 20px;
  left: 30px;
  z-index: 2000;
  padding: 8px 18px;
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  transition: background 0.2s;
}
.back-home-btn:hover {
  background: #1d4ed8;
}
.profile-container {
  max-width: 100vw;
  margin: 0 auto;
  padding: 0 2vw;
  background-color: #fff;
  box-sizing: border-box;
  min-height: 100vh;
}

.profile-layout {
  display: flex;
  min-height: 80vh;
  margin-top: 60px;
}

.profile-sidebar {
  flex: 3;
  max-width: 260px;
  background: #f8fafc;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 32px 0 32px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 32px;
  min-width: 180px;
}

.avatar-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32px;
}
.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e2e8f0;
  margin-bottom: 12px;
}
.username {
  font-weight: 600;
  color: #333;
  font-size: 18px;
}
.profile-menu {
  list-style: none;
  padding: 0;
  width: 100%;
}
.profile-menu li {
  width: 100%;
  padding: 14px 0 14px 32px;
  color: #475569;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
  border-left: 4px solid transparent;
}
.profile-menu li.active {
  background: #e0e7ef;
  color: #2563eb;
  border-left: 4px solid #2563eb;
}
.profile-menu .logout-btn {
  color: #ef4444;
  margin-top: 40px;
  font-weight: 600;
  border-left: 4px solid transparent;
}
.profile-menu .logout-btn:hover {
  background: #fee2e2;
  color: #b91c1c;
}
.profile-main {
  flex: 7;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 40px 32px;
  min-height: 400px;
}

.address-item {
  padding: 16px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.default-address {
  border: 1px solid #2563eb;
  background-color: #eff6ff;
}

.default-tag {
  background-color: #2563eb;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
  margin-right: 8px;
}

.address-actions {
  display: flex;
  gap: 8px;
}

.address-actions button {
  padding: 6px 12px;
  border: none;
  background: none;
  cursor: pointer;
  color: #475569;
  font-size: 14px;
}

.address-actions button:hover {
  color: #2563eb;
}

.add-address-btn {
  margin-top: 20px;
  padding: 10px 16px;
  background-color: #2563eb;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.address-form-container {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
}

.address-form .form-row {
  margin-bottom: 16px;
}

.address-form label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
}

.address-form input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
}

.form-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.form-buttons button {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.form-buttons button[type="submit"] {
  background-color: #2563eb;
  color: white;
}

.form-buttons button[type="button"] {
  background-color: #f1f5f9;
  color: #475569;
}
</style>
<style scoped>
.avatar-upload-box {
  display: flex;
  align-items: center;
  gap: 16px;
}
.avatar-preview {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 1.5px solid #e2e8f0;
}
</style>
<style scoped>
.base-info-form {
  max-width: 400px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.form-row {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.form-row label {
  color: #475569;
  font-weight: 500;
}
.form-row input {
  padding: 10px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 15px;
}
.form-row input:disabled {
  background: #f1f5f9;
}
.save-btn {
  margin-top: 10px;
  padding: 10px;
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
}
.save-btn:hover {
  background: #1d4ed8;
}
.base-info-msg {
  color: #16a34a;
  margin-left: 10px;
}

.address-list {
  margin-bottom: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.address-item {
  padding: 16px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  transition: box-shadow 0.2s;
}

.address-item:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

.address-info {
  flex: 1;
}

.address-recipient {
  font-weight: 600;
  margin-bottom: 8px;
  color: #1e293b;
}

.address-detail {
  color: #475569;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: flex-end;
}

.default-tag {
  background: #dbeafe;
  color: #2563eb;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-bottom: 8px;
  display: inline-block;
}

.address-actions button {
  padding: 6px 12px;
  border: none;
  background: #f1f5f9;
  color: #475569;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.address-actions button:hover {
  background: #e2e8f0;
}

.address-actions button:nth-child(3) {
  color: #2563eb;
  background: #e0e7ff;
}

.address-actions button:nth-child(3):hover {
  background: #c7d2fe;
}

.address-actions button:last-child {
  color: #dc2626;
  background: #fee2e2;
}

.address-actions button:last-child:hover {
  background: #fecaca;
}

.add-address-btn {
  padding: 10px 16px;
  background: #2563eb;
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 600;
  transition: background 0.2s;
}

.add-address-btn:hover {
  background: #1d4ed8;
}

.no-address {
  text-align: center;
  padding: 32px 0;
  color: #64748b;
}

.address-form-container {
  margin-top: 24px;
  padding: 20px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: #f8fafc;
}

.address-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-width: 400px;
}

.form-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 12px;
}

.form-buttons button {
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background 0.2s;
}

.form-buttons button:first-child {
  background: #2563eb;
  color: #fff;
  border: none;
}

.form-buttons button:first-child:hover {
  background: #1d4ed8;
}

.form-buttons button:last-child {
  background: #f1f5f9;
  color: #475569;
  border: 1px solid #e2e8f0;
}

.form-buttons button:last-child:hover {
  background: #e2e8f0;
}
</style>
